package xyz.blushyes.interceptor;


import lombok.RequiredArgsConstructor;
import org.jetbrains.annotations.NotNull;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import static xyz.blushyes.constant.AuthCost.*;

@Component
@RequiredArgsConstructor
public class AuthInterceptor implements HandlerInterceptor {
    private final StringRedisTemplate stringRedisTemplate;

    @Override
    public boolean preHandle(@NotNull HttpServletRequest request, @NotNull HttpServletResponse response, @NotNull Object handler) throws Exception {
        // 获取请求头的 token
        String token = request.getHeader(AUTH_HEADER);
        String someInfo = stringRedisTemplate.opsForValue().get(TOKEN_PREFIX + token);

        // 如果未查询到，则说明未登录，直接拒绝请求
        if (null == someInfo) {
            response.setStatus(403);
            response.setContentType("text/html");
            response.setCharacterEncoding("utf-8");
            response.getWriter().println(NOT_LOGIN);
            return false;
        }

        // 如果查询到了，进行某些操作比如存 ThreadLocal
        // ...

        return true;
    }
}
